package club.web51.classroominteractiontoolsadmin.Services;

import club.web51.classroominteractiontoolsadmin.DO.MainDO.Sign;
import club.web51.classroominteractiontoolsadmin.DO.RelationDO.Section_User;
import club.web51.classroominteractiontoolsadmin.DO.RelationDO.Sign_User;
import club.web51.classroominteractiontoolsadmin.Enums.MsgEnum;
import club.web51.classroominteractiontoolsadmin.Exceptions.ErrDataException;
import club.web51.classroominteractiontoolsadmin.Repositories.*;
import club.web51.classroominteractiontoolsadmin.Utils.SFWhere;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname SignDataService
 * @Description TODO
 * @Created by cxk
 */
@Service
public class SignDataAddService {
    @Resource
    SignRepository signRepository;
    @Resource
    Sign_UserRepository sign_userRepository;
    @Resource
    UserRepository userRepository;
    @Resource
    SectionRepository sectionRepository;
    @Resource
    Section_UserRepository section_userRepository;
    /**
     * @param cid 课程ID
     * @param seid 群组ID
     * @param siid 签到条目ID
     */
    public void addStudent(Long cid,Long seid,String siid){
        //签到条目检索
        Sign sign = signRepository.getOne(siid);
        //判定签到截止
        if(sign.getDeadline().after(new Date())){
            throw new ErrDataException(MsgEnum.ERROR_DATA_EXCEPT);
        }
        //找到群组的所有学生
        Section_User section_user = Section_User.builder().cid(cid).seid(seid).build();
        List<Section_User> section_users = section_userRepository.findAll(SFWhere.and(section_user).build());
        //筛选uid并且去重
        List<Long> student_id = section_users.stream().map(Section_User::getUid).distinct().collect(Collectors.toList());
        //构造数据库数据
        Sign_User.Sign_UserBuilder sign_user = Sign_User.builder().cid(cid).sign_type(sign.getKind()).status(0);
        //批量保存+添加
        for(Long uid : student_id){
            sign_userRepository.save(sign_user.uid(uid).build());
        }
    }

    /**
     * 添加单个学生签到条目
     * @param cid
     * @param siid
     * @param uid
     */
    public void addStudent(Long cid,String siid,Long uid){
        Sign_User sign_user = Sign_User.builder().cid(cid).siid(siid).uid(uid).status(1).build();
        //已经添加过，不再添加
        if(sign_userRepository.count(SFWhere.and(sign_user).build()) != 0L){
            return;
        }
        sign_userRepository.save(sign_user);
    }
}
